package me.zhengjie.modules.devicemap.service.impl;

import me.zhengjie.modules.devicemap.domain.DeviceMap;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.modules.devicemap.repository.DeviceMapRepository;
import me.zhengjie.modules.devicemap.service.DeviceMapService;
import me.zhengjie.modules.devicemap.service.dto.DeviceMapDTO;
import me.zhengjie.modules.devicemap.service.mapper.DeviceMapMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;

/**
* @author 张鹏
* @date 2019-06-03
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DeviceMapServiceImpl implements DeviceMapService {

    @Autowired
    private DeviceMapRepository deviceMapRepository;

    @Autowired
    private DeviceMapMapper deviceMapMapper;

    @Override
    public DeviceMapDTO findById(Long id) {
        Optional<DeviceMap> deviceMap = deviceMapRepository.findById(id);
        ValidationUtil.isNull(deviceMap,"DeviceMap","id",id);
        return deviceMapMapper.toDto(deviceMap.get());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DeviceMapDTO create(DeviceMap resources) {
        return deviceMapMapper.toDto(deviceMapRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DeviceMap resources) {
        Optional<DeviceMap> optionalDeviceMap = deviceMapRepository.findById(resources.getId());
        ValidationUtil.isNull( optionalDeviceMap,"DeviceMap","id",resources.getId());

        DeviceMap deviceMap = optionalDeviceMap.get();
        // 此处需自己修改
        resources.setId(deviceMap.getId());
        deviceMapRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        deviceMapRepository.deleteById(id);
    }
}